/*
 * Copyright (c) 2012 Jonathan Tyers
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package uk.org.uplink.guicemodulescanner.reflections;

import java.util.regex.Pattern;

import org.reflections.Reflections;
import org.reflections.scanners.TypeAnnotationsScanner;
import org.reflections.util.ClasspathHelper;
import org.reflections.util.ConfigurationBuilder;
import org.reflections.util.FilterBuilder;

import uk.org.uplink.guicemodulescanner.SimpleReflectionInstanceCreator;
import uk.org.uplink.guicemodulescanner.configuration.Configuration;

/**
 * Creates instances of {@link ReflectionsModuleScanner}.
 * 
 * @author jonny
 */
public class ReflectionsModuleScannerFactory {
	public static ReflectionsModuleScanner create(final Configuration configuration) {
		Reflections reflections = new Reflections(convertConfiguration(configuration));

		return new ReflectionsModuleScanner(reflections, new SimpleReflectionInstanceCreator());
	}

	private static ConfigurationBuilder convertConfiguration(final Configuration configuration) {
		ConfigurationBuilder builder = new ConfigurationBuilder();
		FilterBuilder filterBuilder = new FilterBuilder();

		/* configure the builders with default, minimal, settings */
		// @formatter:off
		builder = new org.reflections.util.ConfigurationBuilder()
		.setUrls(ClasspathHelper.forJavaClassPath())
		.setScanners(new TypeAnnotationsScanner());

		builder.filterInputsBy(filterBuilder);
		// @formatter:on

		for (String includePackage : configuration.getIncludePackages()) {
			filterBuilder.include(quote(includePackage));
		}
		for (String excludePackage : configuration.getExcludePackages()) {
			filterBuilder.exclude(quote(excludePackage));
		}

		return builder;
	}

	/**
	 * Rudimentary method to produce regular expressions that match the given string, similar to {@link Pattern#quote(String)}.
	 * This method is specifically intended for java package names (which can only contain alphanumeric characters and dots).
	 * 
	 * @param str
	 * @return
	 */
	private static String quote(final String str) {
		return "^" + str.replace(".", "\\.") + ".*";
	}
}
